import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'
import AliyunTextRewriter from '@/lib/aliyunTextRewriter'

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const user = await getUserFromRequest(request)
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const {
      videoIds,
      prompt
    } = await request.json()

    if (!videoIds || !Array.isArray(videoIds) || videoIds.length === 0) {
      return NextResponse.json(
        { error: '请选择要改写的视频' },
        { status: 400 }
      )
    }

    if (!prompt || !prompt.trim()) {
      return NextResponse.json(
        { error: '请输入改写提示词' },
        { status: 400 }
      )
    }

    console.log(`🚀 开始批量改写文案，视频数量: ${videoIds.length}`)
    console.log('💬 改写提示词:', prompt)

    // 获取选中视频的文案
    const videos = await prisma.tikTokVideo.findMany({
      where: {
        id: { in: videoIds }
      },
      include: {
        textExtractions: {
          where: {
            status: 'completed'
          },
          orderBy: {
            createdAt: 'desc'
          },
          take: 1 // 只取最新的一个成功提取结果
        }
      }
    })

    if (videos.length === 0) {
      return NextResponse.json(
        { error: '未找到选中的视频' },
        { status: 404 }
      )
    }

    // 过滤出有文案的视频
    const videosWithText = videos.filter(video =>
      video.textExtractions.length > 0 &&
      video.textExtractions[0].extractedText &&
      video.textExtractions[0].extractedText.trim().length > 0
    )

    if (videosWithText.length === 0) {
      return NextResponse.json(
        { error: '选中的视频都没有提取到文案' },
        { status: 400 }
      )
    }

    console.log(`📝 找到 ${videosWithText.length} 个有文案的视频`)

    // 立即返回响应，告知用户改写已开始
    const response = NextResponse.json({
      success: true,
      message: `改写任务已启动，正在后台处理 ${videosWithText.length} 个视频的文案改写`,
      taskStarted: true,
      videosCount: videosWithText.length
    })

    // 在后台异步执行改写任务
    setImmediate(async () => {
      console.log('🔄 开始后台改写任务...')

      // 初始化文案改写服务
      const rewriter = new AliyunTextRewriter()

      // 逐个改写文案
      for (const video of videosWithText) {
        const originalText = video.textExtractions[0].extractedText

        try {
          console.log(`🎯 开始改写视频 ${video.id} 的文案...`)
          console.log(`📄 原文案: ${originalText.substring(0, 100)}${originalText.length > 100 ? '...' : ''}`)

          const rewriteResult = await rewriter.rewriteText({
            originalText,
            prompt
          })

          if (rewriteResult.success && rewriteResult.rewrittenText) {
            // 保存改写结果到数据库
            const rewrittenText = await prisma.rewrittenText.create({
              data: {
                videoId: video.id,
                originalTextId: video.textExtractions[0].id,
                originalText,
                rewrittenText: rewriteResult.rewrittenText,
                style: 'custom',
                tone: 'custom',
                length: 'custom',
                requirements: prompt,
                requestId: rewriteResult.requestId || '',
                createdBy: user.id
              }
            })

            console.log(`✅ 视频 ${video.id} 文案改写完成，保存ID: ${rewrittenText.id}`)
            console.log(`📝 改写结果: ${rewriteResult.rewrittenText.substring(0, 100)}${rewriteResult.rewrittenText.length > 100 ? '...' : ''}`)
          } else {
            console.log(`❌ 视频 ${video.id} 文案改写失败: ${rewriteResult.error}`)
          }
        } catch (error) {
          console.error(`💥 视频 ${video.id} 改写异常:`, error)
        }

        // 添加延迟避免API限制
        await new Promise(resolve => setTimeout(resolve, 1000))
      }

      console.log('🎉 后台改写任务全部完成！')
    })

    return response

  } catch (error) {
    console.error('Batch rewrite error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : '改写失败' },
      { status: 500 }
    )
  }
}
